<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
      <el-form-item label="优惠券名称" prop="name" class="search-item">
        <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="优惠券编码" prop="code" class="search-item">
        <el-input v-model="queryParams.code" placeholder="请输入优惠券编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="type" class="search-item">
        <el-select v-model="queryParams.type" placeholder="请选择优惠券类型" clearable>
          <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用范围" prop="useScope" class="search-item">
        <el-select v-model="queryParams.useScope" placeholder="请选择使用范围" clearable>
          <el-option v-for="dict in useScopeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" class="search-item">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-item">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:template:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:template:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:template:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="优惠券ID" align="center" prop="id" width="80" />
      <el-table-column label="优惠券名称" align="left" prop="name" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="优惠券编码" align="center" prop="code" width="120" />
      <el-table-column label="优惠券类型" align="center" prop="typeName" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : scope.row.type === 2 ? 'warning' : 'info'">
            {{ scope.row.typeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额/折扣率" align="center" prop="discount" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.type === 2 ? 'warning' : 'success'">
            {{ scope.row.type === 2 ? scope.row.discount + '%' : '¥' + scope.row.discount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最低消费金额" align="center" prop="minPoint" width="120">
        <template #default="scope">
          <el-tag type="info">¥{{ scope.row.minPoint }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用范围" align="center" prop="useScopeName" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.useScope === 0 ? 'success' : scope.row.useScope === 1 ? 'warning' : 'info'">
            {{ scope.row.useScopeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" min-width="200">
        <template #default="scope">
          <div class="time-wrapper">
            <div class="time-item">
              <span class="time-label">开始：</span>
              <span class="time-value">{{ scope.row.startTime }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">结束：</span>
              <span class="time-value">{{ scope.row.endTime }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发行总量" align="center" prop="totalCount" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.totalCount === -1 ? 'info' : 'success'">
            {{ scope.row.totalCount === -1 ? '不限量' : scope.row.totalCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="已使用/已领取" align="center" width="120">
        <template #default="scope">
          <div class="count-wrapper">
            <el-tag type="danger" size="small">{{ scope.row.usedCount }}</el-tag>
            <span class="count-separator">/</span>
            <el-tag type="success" size="small">{{ scope.row.receiveCount }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120" fixed="right">
        <template #default="scope">
          <div class="status-wrapper">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              @change="handleStatusChange(scope.row)"
            />
            <span class="status-text" :class="{ 'is-active': scope.row.status === 1 }">
              {{ scope.row.status === 1 ? '已启用' : '已禁用' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button v-hasPermi="['coupon:template:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['coupon:template:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改优惠券模板对话框 -->
    <el-dialog v-model="open" :title="title" width="600px" append-to-body>
      <el-form ref="templateFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入优惠券编码" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" @change="handleTypeChange">
            <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="form.type === 2 ? '折扣率' : '优惠金额'" prop="discount">
          <el-input-number
            v-model="form.discount"
            :precision="2"
            :step="0.1"
            :min="0"
            :max="form.type === 2 ? 100 : undefined"
            :controls="false"
            style="width: 200px"
          />
          <span class="ml-2">{{ form.type === 2 ? '%' : '元' }}</span>
        </el-form-item>
        <el-form-item label="最低消费金额" prop="minPoint">
          <el-input-number v-model="form.minPoint" :precision="2" :step="0.1" :min="0" :controls="false" style="width: 200px" />
          <span class="ml-2">元</span>
        </el-form-item>
        <el-form-item label="使用范围" prop="useScope">
          <el-select v-model="form.useScope" placeholder="请选择使用范围" @change="handleUseScopeChange">
            <el-option v-for="dict in useScopeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.useScope !== 0" label="范围选择" prop="scopeId">
          <el-select-v2
            v-model="form.scopeId"
            :options="scopeOptions"
            placeholder="请选择范围"
            style="width: 100%"
            multiple
            :props="{
              label: 'name',
              value: 'id'
            }"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="validTime">
          <el-date-picker
            v-model="validTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            style="width: 100%"
            @change="handleValidTimeChange"
          />
        </el-form-item>
        <el-form-item label="发行总量" prop="totalCount">
          <el-input-number v-model="form.totalCount" :min="-1" :controls="false" style="width: 200px" />
          <span class="ml-2">-1表示不限量</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">未启用</el-radio>
            <el-radio :value="1">已启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listTemplate, getTemplate, addTemplate, updateTemplate, delTemplate } from '@/api/coupon/template';
import { listBrand } from '@/api/product/brand';
import { listCategory } from '@/api/product/category';
import { listProduct } from '@/api/product/product';
import type { CouponTemplateQuery, CouponTemplateVO, CouponTemplateForm, CouponTemplateSubmitForm } from '@/api/coupon/template/types';
import type { BrandVO } from '@/api/product/brand/types';
import type { CategoryVO } from '@/api/product/category/types';
import type { CategoryQuery } from '@/api/product/category/types';
import type { ProductBrandQuery } from '@/api/product/brand/types';

// 优惠券类型选项
const typeOptions = [
  { value: 1, label: '满减券' },
  { value: 2, label: '折扣券' },
  { value: 3, label: '立减券' }
];

// 使用范围选项
const useScopeOptions = [
  { value: 0, label: '全场通用' },
  { value: 1, label: '指定品类' },
  { value: 2, label: '指定商品' }
];

// 状态选项
const statusOptions = [
  { value: 0, label: '未启用' },
  { value: 1, label: '已启用' },
  { value: 2, label: '已结束' }
];

// 定义选项类型
interface OptionItem {
  id: number;
  name: string;
}

// 范围选项
const scopeOptions = ref<OptionItem[]>([]);
// 范围选项缓存
const scopeOptionsCache = ref<Record<number, OptionItem[]>>({});

const loading = ref(false);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const templateList = ref<CouponTemplateVO[]>([]);
const open = ref(false);
const title = ref('');
const validTime = ref<[string, string]>(['', '']);
const templateFormRef = ref();

const queryParams = reactive<CouponTemplateQuery>({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  type: undefined,
  useScope: undefined,
  status: undefined
});

const form = reactive<CouponTemplateForm>({
  name: '',
  code: '',
  type: 1,
  discount: 0,
  minPoint: 0,
  useScope: 0,
  scopeId: [] as number[],
  startTime: '',
  endTime: '',
  totalCount: -1,
  status: 0
});

const rules = {
  name: [
    { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '优惠券名称长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '优惠券编码不能为空', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_]+$/, message: '优惠券编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  type: [{ required: true, message: '优惠券类型不能为空', trigger: 'change' }],
  discount: [
    { required: true, message: '优惠金额/折扣率不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '优惠金额/折扣率必须大于0', trigger: 'blur' }
  ],
  minPoint: [
    { required: true, message: '最低消费金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '最低消费金额必须大于0', trigger: 'blur' }
  ],
  useScope: [{ required: true, message: '使用范围不能为空', trigger: 'change' }],
  scopeId: [{ required: true, message: '范围选择不能为空', trigger: 'change' }],
  totalCount: [{ required: true, message: '发行总量不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
};

// 获取类型名称
const getTypeName = (type: number) => {
  return typeOptions.find((item) => item.value === type)?.label || '';
};

// 获取使用范围名称
const getUseScopeName = (useScope: number) => {
  return useScopeOptions.find((item) => item.value === useScope)?.label || '';
};

// 获取状态名称
const getStatusName = (status: number) => {
  return statusOptions.find((item) => item.value === status)?.label || '';
};

/** 查询优惠券模板列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTemplate(queryParams);
    // 处理返回数据，添加名称字段
    templateList.value = res.rows.map((item) => ({
      ...item,
      typeName: getTypeName(item.type),
      useScopeName: getUseScopeName(item.useScope),
      statusName: getStatusName(item.status),
      discount: Number(item.discount),
      minPoint: Number(item.minPoint),
      totalCount: Number(item.totalCount)
    }));
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.name = undefined;
  queryParams.code = undefined;
  queryParams.type = undefined;
  queryParams.useScope = undefined;
  queryParams.status = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CouponTemplateVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 先显示对话框
  open.value = true;
  title.value = '添加优惠券模板';
  // 如果默认选择了使用范围，加载对应的选项
  if (form.useScope !== 0) {
    loadScopeOptions(form.useScope);
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CouponTemplateVO) => {
  reset();

  const id = row?.id || ids.value[0];
  const res = await getTemplate(id);

  // 先赋值基本信息
  Object.assign(form, {
    name: res.data.name,
    id: res.data.id,
    code: res.data.code,
    type: res.data.type,
    discount: Number(res.data.discount),
    minPoint: Number(res.data.minPoint),
    totalCount: Number(res.data.totalCount),
    scopeId: [], // 先清空，等下再赋值
    startTime: res.data.startTime,
    endTime: res.data.endTime,
    status: res.data.status
  });
  validTime.value = [form.startTime, form.endTime];

  // 如果选择了使用范围，加载对应的选项并赋值scopeId
  if (res.data.useScope !== 0) {
    await loadScopeOptions(res.data.useScope);
    form.scopeId = res.data.scopeId ? res.data.scopeId.split(',').map(Number) : [];
  }

  open.value = true;
  title.value = '修改优惠券模板';
};

/** 提交按钮 */
const submitForm = async () => {
  console.log(form);
  if (!templateFormRef.value) return;
  await templateFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const submitData: CouponTemplateSubmitForm = {
        ...form,
        scopeId: form.scopeId.join(',')
      };

      let res;
      if (form.id) {
        res = await updateTemplate(submitData);
      } else {
        res = await addTemplate(submitData);
      }
      if (res.code === 200) {
        ElMessage.success(form.id ? '修改成功' : '新增成功');
        open.value = false;
        getList();
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CouponTemplateVO) => {
  const id = row?.id || ids.value[0];
  await ElMessageBox.confirm('是否确认删除优惠券模板编号为"' + id + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  const res = await delTemplate(id);
  if (res.code === 200) {
    ElMessage.success('删除成功');
    getList();
  }
};

/** 表单重置 */
const reset = () => {
  form.id = undefined;
  form.name = '';
  form.code = '';
  form.type = 1;
  form.discount = 0;
  form.minPoint = 0;
  form.useScope = 0;
  form.scopeId = [];
  form.startTime = '';
  form.endTime = '';
  form.totalCount = -1;
  form.status = 0;
  validTime.value = ['', ''];
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 有效期变更 */
const handleValidTimeChange = (val: [string, string]) => {
  if (val) {
    form.startTime = val[0];
    form.endTime = val[1];
  } else {
    form.startTime = '';
    form.endTime = '';
  }
};

/** 优惠券类型变更 */
const handleTypeChange = (val: number) => {
  if (val === 2) {
    form.discount = Math.min(form.discount, 100);
  }
};

/** 使用范围变更 */
const handleUseScopeChange = async (val: number) => {
  // 先清空范围选择的数据
  form.scopeId = [];
  scopeOptions.value = [];
  // 再加载新的选项数据
  await loadScopeOptions(val);
};

/** 加载范围选项 */
const loadScopeOptions = async (useScope: number) => {
  // 如果缓存中有数据，直接使用缓存
  if (scopeOptionsCache.value[useScope]) {
    scopeOptions.value = scopeOptionsCache.value[useScope];
    return;
  }

  let res;
  if (useScope === 1) {
    // 获取品类列表
    res = await listCategory({ status: 1 } as CategoryQuery);
    const data = res.rows.map((item: any) => ({ id: item.id, name: item.name }));
    scopeOptions.value = data;
    scopeOptionsCache.value[useScope] = data;
  } else if (useScope === 2) {
    // 获取商品列表
    res = await listProduct({ status: 1 } as any);
    const data = res.rows.map((item: any) => ({ id: item.id, name: item.name }));
    scopeOptions.value = data;
    scopeOptionsCache.value[useScope] = data;
  } else {
    scopeOptions.value = [];
  }
};

/** 修改优惠券模板状态 */
function handleStatusChange(row: CouponTemplateVO) {
  const text = row.status === 1 ? '启用' : '停用';
  row.statusLoading = true;
  updateTemplate({
    id: row.id,
    name: row.name,
    code: row.code,
    type: row.type,
    discount: row.discount,
    minPoint: row.minPoint,
    useScope: row.useScope,
    scopeId: row.scopeId,
    startTime: row.startTime,
    endTime: row.endTime,
    totalCount: row.totalCount,
    status: row.status
  })
    .then(() => {
      ElMessage.success(text + '成功');
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1;
    })
    .finally(() => {
      row.statusLoading = false;
    });
}

onMounted(() => {
  getList();
  // 只预加载品类数据，因为商品数据量可能很大
  loadScopeOptions(1);
});
</script>

<style scoped>
.ml-2 {
  margin-left: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.search-item {
  margin-bottom: 0;
  margin-right: 0;
}

.search-item :deep(.el-form-item__label) {
  width: 80px;
  text-align: right;
  padding-right: 8px;
}

.search-item :deep(.el-input),
.search-item :deep(.el-select) {
  width: 200px;
}

.status-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-text {
  font-size: 13px;
  color: #909399;

  &.is-active {
    color: #67c23a;
  }
}

.time-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
}

.time-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.time-label {
  color: #909399;
  font-size: 13px;
}

.time-value {
  color: var(--el-text-color-primary);
  font-size: 13px;
}

.count-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.count-separator {
  color: #909399;
  margin: 0 2px;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
  --el-switch-off-color: #f56c6c;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-bg-color-page);
}

:deep(.el-table th) {
  font-weight: 600;
  background-color: var(--el-bg-color-page);
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-tag--small) {
  height: 20px;
  line-height: 20px;
  padding: 0 6px;
}
</style>
